package configuration

import (
	"encoding/json"
	awardM "kop/modules/award/models"
	"kop/modules/configuration/client"
	"kop/pb"
	"kop/util/log"
)

var rankingAwardList []RankingAwardConf

func init() {

	if err := json.Unmarshal(client.Load("ActivityRank"), &rankingAwardList); err != nil {
		panic(err)
	}

	log.Info("Load ActivityRank.json success.")
}

type RankingAwardConf struct {
	ID            int32 // 索引，无含义
	ActivityID    int32 // 活动ID
	RankMax       int   // 排名最大
	AwardID       int32 // 奖励ID
	LeaderAwardID int32
	MemberAwardID int32
}

func GetAwardsByActivityID(activityID int32) []RankingAwardConf {

	var res []RankingAwardConf
	for _, v := range rankingAwardList {
		if v.ActivityID == activityID {
			res = append(res, v)
		}
	}

	return res
}

func GetRankingConfigs(serverID int32) []ActivityConf {

	var n = 开服第N天(serverID)

	var res []ActivityConf

	if n <= Z8 {
		// open server not over 28 day
		for _, v := range rankingList1 {
			if n >= v.BeginDay && n <= v.ShowDay() {
				v.setTime1(serverID)
				res = append(res, v)
			}
		}
	} else {
		// open server over 28 day
		//var mod = n % rankingList2[len(rankingList2)-1].EndDay
		//if mod == 0 {
		//	mod = n
		//}

		n -= Z8
		//var endDay = rankingList2[len(rankingList2)-1].EndDay
		var mod = n % Z8
		if mod == 0 {
			mod = Z8
		}

		for _, v := range rankingList2 {
			if mod >= v.BeginDay && mod <= v.ShowDay() {
				v.setTime2(serverID)
				res = append(res, v)
			}
		}
	}

	return res
}

func GetRankingAwards(role *pb.Role, activityID int32) map[int32]*pb.Award {

	var res = make(map[int32]*pb.Award)

	for _, r := range GetAwardsByActivityID(activityID) {
		res[int32(r.RankMax)] = awardM.RandAward(role, r.AwardID)
	}

	return res
}

func GetLeaderAwards(activityID int32) map[int32]*pb.Award {

	var res = make(map[int32]*pb.Award)

	for _, r := range GetAwardsByActivityID(activityID) {
		if r.LeaderAwardID != 0 {
			res[int32(r.RankMax)] = awardM.RandAward(&pb.Role{}, r.LeaderAwardID)
		}
	}

	return res
}

func GetMemberAwards(activityID int32) map[int32]*pb.Award {

	var res = make(map[int32]*pb.Award)

	for _, r := range GetAwardsByActivityID(activityID) {
		if r.MemberAwardID != 0 {
			res[int32(r.RankMax)] = awardM.RandAward(&pb.Role{}, r.MemberAwardID)
		}
	}

	return res
}
